<template>
  <el-dialog
    v-model="dialogVisible"
    title="导出 Miniblink 项目"
    width="700px"
    :before-close="handleClose"
  >
    <div class="export-container">
      <!-- 成功提示 -->
      <div v-if="exportSuccess" class="success-container">
        <el-result icon="success" title="导出成功!" sub-title="文件已成功导出到指定位置">
          <template #extra>
            <div class="file-info">
              <strong>导出文件路径:</strong> 
              <div class="path-display">{{ outputFilePath || '(路径未指定)' }}</div>
            </div>
            
            <div class="guide-section">
              <h3>使用指南</h3>
              <p>1. 复制生成的 index.html 文件</p>
              <p>2. 在您的Miniblink项目中引用此文件</p>
              <p>3. 使用以下代码与UI交互:</p>
              
              <el-tabs v-model="activeLanguageTab">
                <el-tab-pane label="C#" name="csharp">
                  <pre class="code-block">{{csharpCode}}</pre>
                  <el-button type="primary" size="small" @click="copyCode('csharp')">
                    复制代码
                  </el-button>
                </el-tab-pane>
                <el-tab-pane label="易语言" name="elang">
                  <pre class="code-block">{{elangCode}}</pre>
                  <el-button type="primary" size="small" @click="copyCode('elang')">
                    复制代码
                  </el-button>
                </el-tab-pane>
              </el-tabs>
            </div>
            
            <div class="actions">
              <el-button @click="openOutputFolder">打开输出文件夹</el-button>
              <el-button type="primary" @click="dialogVisible = false">完成</el-button>
            </div>
          </template>
        </el-result>
      </div>
      
      <!-- 导出步骤 -->
      <div v-else class="export-steps">
        <el-steps :active="currentStep" finish-status="success">
          <el-step title="选择选项" />
          <el-step title="导出" />
        </el-steps>
        
        <!-- 步骤1：设置导出选项 -->
        <div v-if="currentStep === 0" class="step-content">
          <h3>导出设置</h3>
          
          <el-form label-position="top" class="export-form">
            <el-form-item label="项目名称">
              <el-input v-model="projectName" placeholder="输入项目名称" />
            </el-form-item>
            
            <el-form-item label="兼容性选项">
              <el-checkbox v-model="compatibilityMode">
                使用兼容模式（适用于Miniblink等旧版浏览器内核）
              </el-checkbox>
              <div class="tip-text">
                <i class="el-icon-info"></i>
                如果在Miniblink环境中遇到"Unexpected token ..."等语法错误，请启用此选项
              </div>
            </el-form-item>
            
            <el-form-item label="导出路径">
              <div class="path-input">
                <el-input v-model="exportPath" placeholder="导出路径已由上层组件设置" readonly />
              </div>
            </el-form-item>
            
            <el-form-item>
              <el-checkbox v-model="includeSourceCode">
                包含完整源代码
              </el-checkbox>
            </el-form-item>
          </el-form>
        </div>
        
        <!-- 步骤2：导出过程 -->
        <div v-else-if="currentStep === 1" class="step-content">
          <div v-if="exporting" class="exporting-container">
            <h3>正在导出...</h3>
            <el-progress :percentage="exportProgress" />
            <p class="status-message">{{ statusMessage }}</p>
          </div>
          <div v-else-if="exportError" class="error-container">
            <el-result icon="error" title="导出失败" :sub-title="errorMessage">
              <template #extra>
                <el-button @click="currentStep = 0">返回</el-button>
                <el-button type="primary" @click="startExport">重试</el-button>
              </template>
            </el-result>
          </div>
        </div>
        
        <!-- 导航按钮 -->
        <div class="step-actions" v-if="currentStep === 0">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="goToNextStep" :disabled="!isFormValid">下一步</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { ref, computed, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useDesignStore } from '@/stores/designStore';
import { MiniblinkExporter } from '@/utils/miniblinkExporter';

export default {
  name: 'MiniblinkExportWizard',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    exportResult: {
      type: Object,
      default: () => ({ success: false, message: '' })
    }
  },
  emits: ['update:visible', 'close', 'success'],
  
  setup(props, { emit }) {
    const designStore = useDesignStore();
    const dialogVisible = ref(props.visible);
    const currentStep = ref(0);
    const exportSuccess = ref(false);
    const exporting = ref(false);
    const exportError = ref(false);
    const errorMessage = ref('');
    const statusMessage = ref('准备导出...');
    const exportProgress = ref(0);
    const activeLanguageTab = ref('csharp');
    
    // 导出选项
    const projectName = ref(designStore.projectName || 'MyUIProject');
    const exportPath = ref('');
    const includeSourceCode = ref(false);
    const compatibilityMode = ref(true); // 默认启用兼容模式
    
    // 导出结果
    const outputFilePath = ref('');
    
    // 监听visible变化
    watch(() => props.visible, (newValue) => {
      dialogVisible.value = newValue;
      
      // 如果对话框变为可见，则检查是否有导出结果
      if (newValue && props.exportResult && props.exportResult.success) {
        // 直接显示成功状态，跳过选项和导出步骤
        exportSuccess.value = true;
        outputFilePath.value = props.exportResult.filePath || '';
      } else if (newValue) {
        // 重置为初始状态
        currentStep.value = 0;
        exportSuccess.value = false;
        exportError.value = false;
      }
    });
    
    // 监听dialogVisible变化
    watch(dialogVisible, (newValue) => {
      emit('update:visible', newValue);
      if (!newValue) {
        emit('close');
      }
    });

    // 监听导出结果变化
    watch(() => props.exportResult, (newResult) => {
      if (newResult && newResult.success) {
        exportSuccess.value = true;
        outputFilePath.value = newResult.filePath || '';
      } else if (newResult && !newResult.success && newResult.message) {
        exportError.value = true;
        errorMessage.value = newResult.message;
      }
    });
    
    // 验证表单
    const isFormValid = computed(() => {
      return projectName.value && projectName.value.trim() !== '';
    });
    
    // 导出示例代码
    const csharpCode = computed(() => {
      return `using System;
using System.Windows.Forms;

namespace MinibrowserDemo
{
    public partial class MainForm : Form
    {
        private Miniblink.MiniblinkBrowser browser;

        public MainForm()
        {
            InitializeComponent();
            InitializeBrowser();
        }

        private void InitializeBrowser()
        {
            browser = new Miniblink.MiniblinkBrowser();
            browser.Dock = DockStyle.Fill;
            this.Controls.Add(browser);
            
            // 加载导出的HTML文件
            browser.LoadFile("${outputFilePath.value || 'path/to/index.html'}");
            
            // 注册JS回调处理
            browser.RegisterJSCallback("MiniblinkCallback");
            
            // 监听UI事件
            browser.OnJSCallback += (sender, args) => {
                try {
                    // 处理从UI收到的消息
                    Console.WriteLine($"收到UI消息: {args.Message}");
                    
                    // 向UI发送消息示例
                    string cmd = @"
                        window.MiniblinkCallback('{"event":"updateRootComponent","data":{"id":"root","type":"div"}}');
                    ";
                    browser.ExecuteJavaScript(cmd);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"处理UI消息出错: {ex.Message}");
                }
            };
        }
    }
}`;
    });
    
    const elangCode = computed(() => {
      return `.版本 2
.支持库 EThread

.程序集 窗口程序集

.子程序 _按钮1_被单击, 整数型
.局部变量 js, 文本型
    js = "window.MiniblinkCallback('{\"event\":\"updateRootComponent\",\"data\":{\"id\":\"root\",\"type\":\"div\"}}');"
    网页浏览框1.执行JS (js)
.子程序结束

.子程序 _JS回调, 文本型, 文本型
.参数 name, 文本型
.参数 json, 文本型
    调试输出 (json)
    ' 在这里处理从UI接收到的消息
.子程序结束

.子程序 __启动窗口_创建完毕
    ' 加载导出的HTML文件
    网页浏览框1.跳转 ("file:///${outputFilePath.value || 'path/to/index.html'}")
    
    ' 注册JS回调处理
    网页浏览框1.注册JS回调函数 ("MiniblinkCallback", "_JS回调")
.子程序结束`;
    });
    
    // 下一步
    const goToNextStep = () => {
      if (currentStep.value < 1) {
        currentStep.value++;
        
        // 如果进入导出步骤，自动开始导出
        if (currentStep.value === 1 && !exporting.value) {
          startExport();
        }
      }
    };
    
    // 用于跟踪当前导出状态的变量
    const isExportInProgress = ref(false);
    
    // 开始导出
    const startExport = async () => {
      // 防止重复导出
      if (isExportInProgress.value) {
        console.log('导出已经在进行中，忽略重复请求');
        return;
      }
      
      isExportInProgress.value = true;
      exporting.value = true;
      exportError.value = false;
      exportProgress.value = 0;
      statusMessage.value = '准备导出...';
      
      try {
        // 使用App.vue中已经设置好的导出结果
        if (props.exportResult && props.exportResult.success) {
          // 如果已经有成功的导出结果，直接使用它
          exportProgress.value = 100;
          statusMessage.value = '导出成功!';
          outputFilePath.value = props.exportResult.filePath || '';
          
          // 等待进度条完成
          setTimeout(() => {
            exporting.value = false;
            exportSuccess.value = true;
            emit('success', props.exportResult);
            isExportInProgress.value = false;
          }, 500);
          return;
        }
        
        // 否则，准备执行新的导出
        // 准备导出数据
        const components = designStore.canvasComponents;
        
        // 创建导出器实例
        const exporter = new MiniblinkExporter();
        
        // 监听导出进度
        const statusUpdateListener = (event, data) => {
          statusMessage.value = data.status || '处理中...';
          exportProgress.value = Math.min(90, exportProgress.value + 10);
        };
        
        // 添加监听器
        let removeListener = null;
        if (window.electron) {
          // 使用预加载脚本中定义的on方法，它返回一个用于移除监听器的函数
          removeListener = window.electron.ipcRenderer.on('export-status-update', statusUpdateListener);
        }
        
        try {
          // 执行导出
          const result = await exporter.exportProject({
            name: projectName.value,
            components: components, // 直接使用组件，不需要额外包装
            exportPath: exportPath.value,
            includeSourceCode: includeSourceCode.value,
            compatibilityMode: compatibilityMode.value,
            canvasSize: designStore.canvasSize // 添加画布尺寸信息
          });
          
          // 移除监听器
          if (removeListener && typeof removeListener === 'function') {
            removeListener();
          }
          
          if (result.success) {
            // 导出成功
            exportProgress.value = 100;
            statusMessage.value = '导出成功!';
            outputFilePath.value = result.filePath || '';
            
            // 等待进度条完成
            setTimeout(() => {
              exporting.value = false;
              exportSuccess.value = true;
              emit('success', result);
              isExportInProgress.value = false;
            }, 500);
          } else {
            // 导出失败
            throw new Error(result.message || '导出失败');
          }
        } catch (exportError) {
          // 重新抛出错误，让外层catch处理
          throw exportError;
        }
      } catch (error) {
        console.error('导出失败:', error);
        exporting.value = false;
        exportError.value = true;
        errorMessage.value = error.message || '导出过程中发生未知错误';
        isExportInProgress.value = false;
      }
    };
    
    // 复制代码
    const copyCode = (type) => {
      const code = type === 'csharp' ? csharpCode.value : elangCode.value;
      navigator.clipboard.writeText(code)
        .then(() => {
          ElMessage.success('代码已复制到剪贴板');
        })
        .catch(err => {
          console.error('复制失败:', err);
          ElMessage.error('复制失败');
        });
    };
    
    // 打开输出文件夹
    const openOutputFolder = async () => {
      if (outputFilePath.value && window.electron) {
        await window.electron.ipcRenderer.invoke('open-folder', outputFilePath.value);
      } else if (!window.electron) {
        console.warn('在非Electron环境中无法打开文件夹');
        
        // 提供更明确的信息
        const path = outputFilePath.value || exportPath.value;
        if (path) {
          ElMessage.info(`开发模式：无法打开输出文件夹，文件已导出至模拟路径: ${path}`);
        } else {
          ElMessage.info('开发模式：无法打开输出文件夹，请查看控制台获取更多信息');
        }
      }
    };
    
    // 关闭对话框
    const handleClose = () => {
      // 重置状态
      currentStep.value = 0;
      exportSuccess.value = false;
      exporting.value = false;
      exportError.value = false;
      
      dialogVisible.value = false;
    };

    // 如果有导出结果，尽早显示成功界面
    onMounted(() => {
      if (props.exportResult && props.exportResult.success) {
        exportSuccess.value = true;
        outputFilePath.value = props.exportResult.filePath || '';
      }
    });
    
    return {
      dialogVisible,
      currentStep,
      projectName,
      exportPath,
      includeSourceCode,
      compatibilityMode,
      exportSuccess,
      exporting,
      exportError,
      errorMessage,
      statusMessage,
      exportProgress,
      activeLanguageTab,
      outputFilePath,
      csharpCode,
      elangCode,
      isFormValid,
      
      goToNextStep,
      startExport,
      copyCode,
      openOutputFolder,
      handleClose
    };
  }
};
</script>

<style scoped>
.miniblink-export-wizard {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica Neue', 'Arial', 'sans-serif';
}

.wizard-content {
  min-height: 400px;
}

.export-container {
  min-height: 400px;
}

.step-content {
  margin-top: 30px;
  padding: 20px;
}

.export-form {
  max-width: 500px;
  margin: 0 auto;
}

.path-input {
  display: flex;
  align-items: center;
  gap: 10px;
}

.step-actions {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.exporting-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 20px;
}

.status-message {
  margin-top: 20px;
  color: #606266;
}

.error-container {
  padding: 20px;
}

.success-container {
  padding: 20px;
}

.file-info {
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
  border-radius: 4px;
  padding: 12px 15px;
  margin-bottom: 20px;
  color: #67c23a;
}

.path-display {
  font-family: monospace;
  background-color: #fff;
  padding: 8px 12px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  margin-top: 5px;
  word-break: break-all;
  color: #606266;
}

.guide-section {
  margin: 20px 0;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.guide-section h3 {
  margin-bottom: 15px;
  font-size: 18px;
  color: #303133;
}

.guide-section p {
  margin-bottom: 10px;
  line-height: 1.6;
  color: #606266;
}

.code-block {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  padding: 15px;
  border-radius: 4px;
  margin: 15px 0;
  font-family: monospace;
  overflow-x: auto;
  white-space: pre-wrap;
  word-break: break-all;
  line-height: 1.4;
  font-size: 14px;
}

.actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.tip-text {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.4;
}
</style> 